/*
 * Copyright 2008 The Brui Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
 
 package com.googlecode.brui;

import java.awt.GridBagLayout;
import java.awt.LayoutManager;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.swing.JComponent;
import javax.swing.JPanel;

import com.googlecode.brui.components.*;
import com.googlecode.brui.editors.BooleanEditor;
import com.googlecode.brui.editors.IntegerEditor;
import com.googlecode.brui.editors.StringEditor;

public class BeanComponentModel {
	private static final Object[] GETTER_ARGS = new Object[0];
	
	public JComponent getComponent(Class<?> bean, Object instance)
			throws IntrospectionException, IllegalArgumentException,
				IllegalAccessException, InvocationTargetException {
		
		JComponent toReturn = null;
		
		// 0. Preconditions
		if(bean==null || instance==null)
			throw new NullPointerException("You cannot construct a component " +
				"without arguments bean and instance.");
		
		// 1. Get property descriptors for the bean.
		PropertyDescriptor[] beanProperties =
			Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
		
		// 2. For each property
		for(PropertyDescriptor p : beanProperties) {
			Method setter = p.getWriteMethod();
			Method getter = p.getReadMethod();
			if(setter!=null && getter!=null) {
				Class type = p.getPropertyType();
//				JPanel component = new JPanel();
//				component.setLayout(getDefaultLayout());
//				component.add(comp) FIXME
				// 3. Figure out what kind of component we're dealing with and grab the renderer accordingly
				if(type.equals(Integer.class)) {
					new IntegerEditor(getter, setter, instance);
				}
				else if(type.equals(String.class)) {
					new StringEditor(getter, setter, instance);
				}
				else if(type.equals(Boolean.class)) {
					new BooleanEditor(getter, setter, instance);
				}
				else {
					// TODO Add a button to an editor. This button opens another editor.
				}
			}
		}
		return toReturn;
	}
	
	private LayoutManager getDefaultLayout() {
		GridBagLayout toReturn = new GridBagLayout();
//		toReturn.setConstraints(new Component(), constraints) TODO
		return toReturn;
	}
}
